<template>
  <a-modal
    :visible="formVisible"
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div>
      <a-form ref="formRef" :model="form" :rules="rules">
        <a-form-item field="name" label="数据库名称">
          <a-input v-model="form.name" placeholder="请填写" />
        </a-form-item>

        <a-form-item field="username" label="用户名">
          <a-input v-model="form.username" placeholder="请填写" />
        </a-form-item>
        <a-form-item field="password" label="密码">
          <a-input v-model="form.password" placeholder="请填写"></a-input>
        </a-form-item>
        <a-form-item field="url" label="连接地址">
          <a-input v-model="form.url" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { computed, ref } from 'vue';
  import { addDs, updateDs } from '@/api/upms/gen';
  import { useVisible } from '@/hooks/visible';

  const formRef = ref();

  const initData = () => {
    return {
      id: '',
      name: '',
      username: '',
      password: '',
      url: '',
    };
  };

  const rules = {
    name: [
      {
        required: true,
        message: '数据库名称不能为空',
      },
    ],
    username: [
      {
        required: true,
        message: '用户名不能为空',
      },
    ],
    password: [
      {
        required: true,
        message: '密码不能为空',
      },
    ],
    url: [
      {
        required: true,
        message: '连接地址不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const form = ref(props.formData);

  const { formVisible, close, open } = useVisible(props, emit);

  // 判断是编辑还是新增
  const isEdit = computed(() => !!form.value.id);

  const submit = async () => {
    formVisible.value = true;
    const validate = await formRef.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateDs(form.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await addDs(form.value).then(() => {
          Message.success('添加成功');
        });
      }
      form.value = { ...initData };
      formVisible.value = false;
      emit('refresh');
    }
  };

  open(() => {
    const { id } = props.formData;
    if (id) {
      form.value = props.formData;
    } else {
      form.value = initData();
    }
  });
</script>
